package com.bxd.baodan.activity;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bxd.baodan.R;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.util.ETUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.NetUtil.RequestStringListener;
import com.bxd.baodan.util.ResourcesUtil;
import com.bxd.baodan.util.observer.SmsContent;

public class FindPasswordActivity extends BaseActivity implements
        OnClickListener {

    private EditText etAccount, etVcode, etBesure;
    private TextView btnGetVcode;
    private SmsContent content;
    private Boolean isGetVcode = false;
    private int time = -1;
    private RelativeLayout login_btn;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_password);

        setActionBarTitle(ResourcesUtil
                .getStringById(R.string.ab_title_find_password));
        initView();
    }

    private void initView() {
        etAccount = getEditText(R.id.account_text);
        etVcode = getEditText(R.id.regist_vcode_edit);
        etBesure = getEditText(R.id.password);
  //      reSure = getEditText(R.params.repassword);
        btnGetVcode = getTextView(R.id.get_vcode_btn);
        login_btn = getRelativeLayout(R.id.login_btn);
        btnGetVcode.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        // 暂时去掉 弹出键盘
//        etAccount.setFocusable(true);
//        etAccount.requestFocus();
//        new Handler().postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                ETUtil.showSoftKeyboard(FindPasswordActivity.this, etAccount);
//            }
//        }, 2 * 200);

    }

    /**
     * 开始计时
     */
    private void startTime() {
        time = 60;
        isGetVcode = true;
        new Thread() {
            public void run() {
                do {
                    try {
                        Thread.sleep(1 * 1000);
                        if (handler!= null) {
                            handler.sendEmptyMessage(--time);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } while (time > 0 && isGetVcode == true);
                time = -1;
                handler.sendEmptyMessage(--time);
            }
        }.start();
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what > 0) {
                btnGetVcode.setText(msg.what + "秒后重新获取");
                btnGetVcode.setEnabled(false);
            } else {
                btnGetVcode.setText("重新获取验证码");
                btnGetVcode.setEnabled(true);
            }
        }
    };

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.get_vcode_btn:
                attemptIdentifyCode();
                break;
            case R.id.login_btn:// 根据验证码结果进行跳转
                attempChangeTelNo();
                break;

            default:
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void attemptIdentifyCode() {
        if (TextUtils.isEmpty(getString(etAccount))) {
            etAccount.setError("号码不能为空");
            return;
        }
        if (!ETUtil.isMobileNO(etAccount)) {
            etAccount.setError("电话号码不合格");
            return;
        }


        startTime();
        NetUtil netUtil = new NetUtil(this, JsonApi.PCODE);
        netUtil.setParams("phone", etAccount.getText().toString().trim());
        netUtil.setParams("src", "1");
        netUtil.postRequest("正在获取验证码...", new RequestStringListener() {

            @Override
            public void onComplete(String result) {
                Log.i("验证码", result);
                if (JSONUtil.isSuccess(result)) {
                    content = new SmsContent(FindPasswordActivity.this,
                            new Handler(), etVcode);
                    // 注册短信变化监听
                    FindPasswordActivity.this.getContentResolver()
                            .registerContentObserver(
                                    Uri.parse("content://sms/"), true, content);
                } else {

                    if (JSONUtil.getMessage(result).isEmpty()) {
                        if (JSONUtil.getCode(result)== 4) {
                            showToast("验证码发送频繁,稍后重试");
                        }
                    } else {
                        showToast(JSONUtil.getMessage(result));
                    }
                    isGetVcode = false;
                }
            }

        });
    }

    /**
     * 获取注册结果
     */
    private void attempChangeTelNo() {
        if (TextUtils.isEmpty(getString(etAccount))) {
            etAccount.setError("号码不能为空");
            return;
        }
        if (!ETUtil.isMobileNO(etAccount)) {
            etAccount.setError("电话号码不合格");
            return;
        }
        if (TextUtils.isEmpty(getString(etVcode))) {
            etVcode.setError("验证码不能为空");
            return;
        }
        if (TextUtils.isEmpty(getString(etBesure))) {
            etBesure.setError("密码不能为空");
            return;
        }
//        if (TextUtils.isEmpty(getString(reSure))) {
//            reSure.setError("密码不能为空");
//            return;
//        }
//        if (!getString(etBesure).equals(getString(reSure))) {
//            showToast("两次输入密码不一致");
//            return;
//        }
        final String tel = getString(etAccount);
        NetUtil netUtil1 = new NetUtil(this, JsonApi.FIND_PASSWORD);
        netUtil1.setParams("phone", tel);
        netUtil1.setParams("vcode", getString(etVcode));
        netUtil1.setParams("newpassword", getString(etBesure));
        netUtil1.postRequest("", new RequestStringListener() {

            @Override
            public void onComplete(final String result) {

                if (JSONUtil.isSuccess(result)) {
                    showToast("密码修改成功,请进行登录");
                    // openActivity(LoginActivity.class);
                    FindPasswordActivity.this.finish();
                } else {
                    if (JSONUtil.getMessage(result).isEmpty()) {
                        if (JSONUtil.getCode(result)== 4) {
                            showToast("验证码发送频繁,稍后重试");
                        }
                    } else {
                        showToast(JSONUtil.getMessage(result));
                    }
                    isGetVcode = false;
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler!= null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }


}
